package com.sdx.console.draw.web;

import java.util.*;
import java.util.Date;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.utils.JacksonUtils;
import com.ibeetl.admin.core.service.RedisService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.draw.entity.*;
import com.sdx.console.draw.service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 抽奖概率 接口
 */
@RequestMapping("/draw/drawProbability")
@Controller
public class DrawProbabilityController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(DrawProbabilityController.class);
    private static final String MODEL = "/draw/drawProbability";

    private  static final String DRAW_KEY = "TENCENT_DRAW_";
    private  static final String KEY = "TENCENT_DRAW_NUM_";


    @Resource
	private DrawProbabilityService drawProbabilityService;

    @Resource
    private RedisService redisService;

    @Resource
    private SQLManager sqlManager;

    private Random rd =new Random();

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("draw.drawProbability.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("draw.drawProbability.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        DrawProbability drawProbability = drawProbabilityService.queryById(id);
        view.addObject("drawProbability", drawProbability);
		setPageParam(view,request);
		try {
			view.addObject("drawProbabilityJson", JacksonUtils.toJsonString(drawProbability,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("draw.drawProbability.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("draw.drawProbability.query")
    @ResponseBody
    public JsonResult<PageQuery> list(DrawProbability condtion)
    {
        PageQuery page = condtion.getPageQuery();
        drawProbabilityService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,DrawProbability drawProbability,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
        DrawProbability draw = new DrawProbability();
        draw.setType(drawProbability.getType());
        long count = sqlManager.templateCount(draw);
        if (isNew&&count==0) {
            if(drawProbability.getType()==1){
                initDraw(drawProbability);
            }
			drawProbability.setCreatedBy(user.getId().intValue());
			drawProbability.setCreatedName(user.getName());
			drawProbability.setCreatedTime(new Date());
			drawProbability.setUpdatedBy(user.getId().intValue());
			drawProbability.setUpdatedName(user.getName());
			drawProbability.setUpdatedTime(new Date());
			drawProbabilityService.save(drawProbability);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("draw.drawProbability.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)DrawProbability drawProbability,HttpServletRequest request
		)
    {

        return save(true,drawProbability,request
		);
    }

    @PostMapping("/update.json")
    @Function("draw.drawProbability.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  DrawProbability drawProbability,HttpServletRequest request
		) {
		return save(false,drawProbability,request
		);
    }



    @GetMapping("/view.json")
    @Function("draw.drawProbability.query")
    @ResponseBody
    public JsonResult<DrawProbability>queryInfo(Integer id) {
        DrawProbability drawProbability = drawProbabilityService.queryById( id);
        return  JsonResult.success(drawProbability);
    }

    @PostMapping("/delete.json")
    @Function("draw.drawProbability.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        drawProbabilityService.batchDelDrawProbability(idList);
        return JsonResult.success();
    }

    /**
     * 初始化抽奖
     */
    public void initDraw(DrawProbability draw){
        if(draw.getProbability1()!=null){
            Set<Integer> set = draw(draw.getProbability1());
            redisService.resetAtomic(KEY+"1");
            redisService.setValue(DRAW_KEY+"1",set.toString().replaceAll("(?:\\[|null|\\]| +)", ""));

        }
        if(draw.getProbability2()!=null){
            Set<Integer> set = draw(draw.getProbability2());
            redisService.resetAtomic(KEY+"2");
            redisService.setValue(DRAW_KEY+"2",set.toString().replaceAll("(?:\\[|null|\\]| +)", ""));

        }
        if(draw.getProbability3()!=null){
            Set<Integer> set = draw(draw.getProbability3());
            redisService.resetAtomic(KEY+"3");
            redisService.setValue(DRAW_KEY+"3",set.toString().replaceAll("(?:\\[|null|\\]| +)", ""));
        }
    }

    public Set<Integer> draw(int num){
        Set<Integer> set = new HashSet<>();
        while(set.size()<num){
            set.add(rd.nextInt(1000));
        }
        return  set;
    }


    @PostMapping("/updateDraw.json")
    @ResponseBody
    public JsonResult updateDraw(DrawProbability drawProbability,HttpServletRequest request) {
        initDraw(drawProbability);
        CoreUser user = getLoginUser(request);
        drawProbability.setUpdatedBy(user.getId().intValue());
        drawProbability.setUpdatedName(user.getName());
        drawProbability.setUpdatedTime(new Date());
        drawProbabilityService.updateTemplate(drawProbability);
        return JsonResult.success();
    }

}
